<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="用户名" prop="realName">
            <el-input v-model.trim="filterForm.realName" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="身份" prop="identity">
            <el-select v-model.trim="filterForm.identity" placeholder="请选择身份">
              <el-option v-for="dict in dict.type.identity" :key="dict.value"
                         :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="account">
            <el-input v-model.trim="filterForm.account" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" prop="rangeTime">
            <el-date-picker
              v-model="filterForm.rangeTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy/MM/dd HH:mm:ss"
              align="right"
              style="width: 372px">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="flex-1"></div>
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <dt-table
        ref="dtTable"
        class="account-table"
        v-loading="loading"
        :table-opts="tableOpts"
        row-key="id"
        :pagination-data="{
          total: total,
          queryParams: filterForm
        }"
        @pagination="getList"
        @selection-change="selectionChange"
      >
        <template #toolbarBtn>
          <my-dialog-column
            class="dialog-export"
            :query="queryInfo"
            :columns="columns"
            @exportStart="startExport"
            @queryTable="getList"
          />
        </template>
      </dt-table>
    </div>
    <dt-dialog
      :title="formName"
      width="600px"
      :visible.sync="dialogVisible"
      :footerSlot="true"
      @closeDialog="resetTemp"
    >
      <div slot="content" class="form-wrap">
        <el-form :model="form" :rules="rules" ref="form"
                 label-width="0">
          <el-form-item prop="realName">
            <el-input v-model="form.realName" placeholder="请填写用户名" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="account">
            <el-input v-model="form.account" placeholder="请填写手机号码" maxlength="16"
                      :disabled="action == 'edit'"></el-input>
          </el-form-item>
          <!-- <el-form-item prop="pass">
            <el-input type="password" v-model="form.pass" autocomplete="off"
                      placeholder="请设置6-20位登录密码" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-input type="password" v-model="form.checkPass" autocomplete="off"
                      placeholder="再次输入登录密码" maxlength="20"></el-input>
          </el-form-item> -->
          <el-form-item prop="identity">
            <!-- <el-input v-model.number="form.identity" placeholder="设置用户身份"></el-input> -->
            <el-select v-model.trim="form.identity" placeholder="设置用户身份" style="width: 100%">
              <el-option v-for="dict in identityList" :key="dict.code"
                         :label="dict.describe" :value="dict.code" :disabled="dict.disabled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="ascription">
            <el-select v-model="form.ascription" placeholder="设置账户归属" style="width: 100%">
              <el-option v-for="item in ascriptionList" :key="item.id" :label="item.realName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="text-align: center;">
          <el-button type="primary" @click.stop="onSubmit" :loading="buttonLoading">{{ formBtnName}}</el-button>
        </div>
      </template>
    </dt-dialog>
  </div>
</template>

<script>
import myDialogColumn from '@/views/unifiedPayment/components/dialog-column/index.vue'
import { getPage, add, getAscriptions, edit, del, getIdentityList } from '@/api/classroom/accountManage'
import { checkPhone } from '@/framework/utils/validate'
import { encryption } from 'DQBasic-vue-component'

export default {
  name: 'ClassroomAccountManage',
  components: { myDialogColumn },
  provide: {
    showOptArr: [
      'exportFile'
    ]
  },
  dicts: ['identity'],
  data() {
    const validateDPass = (rule, value, callback) => {
      if (value !== this.form.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号/电话'))
      } else if (!checkPhone(value)) {
        callback(new Error('请输入合法的手机号'))
      } else {
        callback()
      }
    }
    return {
      total: 0,
      filterForm: {
        pageNo: 1,
        pageSize: 10,
        rangeTime: [],
        realName: '',
        account: '',
        identity: ''
      },
      tableOpts: {
        rowKey: 'id',
        tableData: [],
        firstTableCol: {
          select: true
        },
        indexTableCol: {
          index: true
        },
        toolbarBtn: [
          {
            label: '新建',
            permission: ['ACCOUNT_MANAGE_ADD_BUTTON'],
            type: 'primary',
            click: () => {
              this.handleAdd()
            }
          }
        ],
        tableCol: [
          {
            prop: 'realName',
            label: '用户名',
            show: true
          },
          {
            prop: 'identity',
            label: '用户身份',
            show: true,
            type: 'dict',
            formatter: (row) => { return this.dict.type.identity }
          },
          {
            prop: 'account',
            label: '手机号',
            show: true
          },
          {
            prop: 'source',
            label: '账户来源',
            show: true
          },
          {
            prop: 'ascriptionName',
            label: '账户归属',
            show: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            show: true
          }
        ],
        operator: {
          width: 200,
          operatorBtn: [
            {
              text: '详情',
              size: 'small',
              click: (row, col, cellValue) => { return this.viewInfo(row) }
            },
            {
              text: '删除',
              permission: ['ACCOUNT_MANAGE_DETAIL_BUTTON'],
              size: 'small',
              click: (row, col, cellValue) => { return this.remove(row) }
            }
          ]
        }
      },
      loading: false,
      selectionRow: [],
      columns: [
        {
          prop: 'realName',
          label: '用户名',
          template: true,
          show: true
        },
        {
          prop: 'identity',
          label: '用户身份',
          template: true,
          show: true
        },
        {
          prop: 'account',
          label: '手机号',
          template: true,
          show: true
        },
        {
          prop: 'source',
          label: '账户来源',
          template: true,
          show: true
        },
        {
          prop: 'ascriptionName',
          label: '账户归属',
          template: true,
          show: true
        },
        {
          prop: 'createTime',
          label: '创建时间',
          template: true,
          show: true
        }
      ],
      queryInfo: {
        menu: '账户管理',
        url: '/onlineClass/userInfo/list',
        params: {},
        method: 'GET',
        selection: ''
      },
      fullLoading: null,
      dialogVisible: false,
      form: {
        realName: '',
        account: '',
        identity: '',
        ascription: ''
      },
      rules: {
        realName: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        account: [
          { required: true, message: '请填写手机号码', trigger: 'blur' },
          { trigger: 'blur', validator: validatePhone }
        ],
        pass: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请设置6-20位登录密码', trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请再次输入登录密码', trigger: 'blur' },
          { validator: validateDPass, trigger: 'blur' }
        ],
        systemName: [{ required: true, message: '请设置用户身份', trigger: 'blur' }],
        ascription: [{ required: true, message: '请设置账户归属', trigger: 'blur' }]
      },
      ascriptionList: [],
      buttonLoading: false,
      action: 'add',
      identityList: []
    }
  },
  computed: {
    pickerOptions() {
      return {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    },
    detailOption() {
      return {
        labelWidth: '140px',
        width: '800px',
        column: 2,
        rows: [],
        data: {}
      }
    },
    formName() {
      return this.action === 'add' ? '新建账户' : '账户详情'
    },
    formBtnName() {
      return this.action === 'add' ? '新建' : '提交'
    }
  },
  mounted() {
    this.refresh()
    this.init()
  },
  methods: {
    init() {
      getAscriptions().then((res) => {
        this.ascriptionList = res.data
      })
      getIdentityList().then((res) => {
        this.identityList = res.data.identityList
      })
    },
    handleAdd() {
      this.action = 'add'
      this.dialogVisible = true
    },
    startExport(type) {
      if (!type) {
        this.fullLoading = this.$loading({
          lock: true,
          text: '正在导出...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      } else {
        this.fullLoading && this.fullLoading.close()
      }
    },
    refresh() {
      this.getList()
    },
    selectionChange(val) {
      this.selectionRow = val
      this.queryInfo.selection = val.map((item) => item.id)
      this.queryInfo.idProp = 'id'
      // this.queryInfo.params.ids = this.queryInfo.selection
    },
    viewInfo(row) {
      this.action = 'edit'
      this.dialogVisible = true
      const { account, identity, ascription, realName, id } = row
      this.form = {
        realName,
        account,
        identity,
        ascription,
        id
      }
    },
    remove(row) {
      this.$dtModal.confirm('请确认是否删除? ').then(() => {
        del({ ids: [row.id] }).then((res) => {
          this.$message.success(res.message)
          this.refresh()
        })
      })
    },
    // 搜索
    handleFilter() {
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.action = 'add'
      this.handleFilter()
    },
    getList() {
      this.loading = true
      if (this.filterForm.rangeTime.length > 0) {
        this.filterForm.createBeginTime = this.filterForm.rangeTime[0]
        this.filterForm.createEndTime = this.filterForm.rangeTime[1]
      } else {
        delete this.filterForm.createBeginTime
        delete this.filterForm.createEndTime
      }
      getPage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    resetTemp() {
      this.form = {
        realName: '',
        account: '',
        identity: '',
        ascription: ''
      }
      this.$refs.form.resetFields()
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.action == 'add') {
            this.form.sourceType = '1'
            const data = encryption({ data: this.form })
            add(data).then((res) => {
              this.$message.success(res.message)
              this.refresh()
              this.dialogVisible = false
              this.buttonLoading = false
            }).catch(() => {
              this.buttonLoading = false
            })
          } else {
            const data = encryption({ data: this.form })
            edit(data).then((res) => {
              this.$message.success(res.message)
              this.refresh()
              this.dialogVisible = false
              this.buttonLoading = false
            }).catch(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.account-table {
  ::v-deep .flex-1 {
    display: none;
  }
  ::v-deep .table-opt-container {
    // justify-content: space-between;
    position: relative;
  }
  ::v-deep .el-date-editor .el-range-input {
    width: 40%;
  }
}
.dialog-export {
  position: absolute;
  right: 0;
}
.form-wrap {
  padding: 0 50px;
}
</style>
